/**
 *  @author Morozan Ion
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.dddforandroid.servlets;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dddforandroid.classes.NotePad.Notes;
import com.dddforandroid.crud.PMF;
import com.dddforandroid.util.Util;
import com.google.appengine.api.NamespaceManager;

@SuppressWarnings("serial")
public class Add extends HttpServlet {

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param req
	 *            servlet request
	 * @param resp
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		getServletContext().getRequestDispatcher("/").forward(req, resp);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		/* Generate an unique identifier */
		String id = UUID.randomUUID().toString();

		/* Get the content of the fileds */
		String name = request.getParameter("name");
		String note = request.getParameter("note");
		String Sdate = request.getParameter("date");
		String identifer = request.getParameter("identifer");


		/** Create a new object */
		Notes task = null;

		/** Get information about current logged in user id*/
		Util user = new Util();
		/** Create a namespace for current loggedin user. */
		NamespaceManager.set(user.getUserId());
		
		/* Get the instance of the Database */
		PersistenceManager db = PMF.get().getPersistenceManager();

		/* keep Database consistent */
		Transaction transaction = db.currentTransaction();

		DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		Date date = null;
		Date currentDate = new Date();
		
		/*
		 * if the user decide not to enter the date, the system will add the
		 * current date
		 */
		if (Sdate.isEmpty()) {
			date = new Date();
		} else {
			try {
				date = (Date) formatter.parse(Sdate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		if (!identifer.isEmpty()) {
			try {
				try {
					transaction.begin();
					/* Get desired note from DB by id */
					task = db.getObjectById(Notes.class, identifer);
					transaction.commit();

					/**
					 * Update the content of the task if the user doesn't enter
					 * the date, than previous date will be keep
					 */
					if (!Sdate.isEmpty()) {
						task.setCreatedDate(date);
					}
					task.setTitle(name);
					task.setNote(note);

					transaction.begin();
					/* update desired Task */
					db.makePersistent(task);
					transaction.commit();

				} catch (Exception ex) {
					/* if smth went wrong */
					if (transaction.isActive()) {
						transaction.rollback();
					}
				}
			} finally {
				/* close the DB in a consistent state */
				db.close();
			}
			response.setHeader("Refresh", "1");
			response.sendRedirect("/");
			
			/* Name of the task is mandatory */
		} else if (name.isEmpty()) {
			request.setAttribute("errorMessage", "<font size=\"3\" "
					+ "face=\"arial\" color=\"red\">"
					+ "Name required! </font>");
			RequestDispatcher rd = request.getRequestDispatcher("/");
			rd.forward(request, response);
			/* Verify if the date is correct(not late than current date) */
		} else if (date.compareTo(currentDate) == -1) {
			request.setAttribute("errorMessage", "<font size=\"3\" "
					+ "face=\"arial\" color=\"red\">" + "Invalid date! </font>");
			RequestDispatcher rd = request.getRequestDispatcher("/");
			rd.forward(request, response);
		} else {
			/* Add a new Task */
			task = new Notes(id, name, note, date);

			try {
				try {
					transaction.begin();
					/* add desired Task */
					db.makePersistent(task);
					transaction.commit();
				} catch (Exception ex) {
					/* if smth went wrong */
					if (transaction.isActive()) {
						transaction.rollback();
					}
				}
			} finally {
				db.close();
			}
			response.setHeader("Refresh", "1");
			response.sendRedirect("/");
		}
		
	}
}
